import { defineStore } from 'pinia'
import { loginReq, logoutReq, getInfo } from '@/api/login/index'
import router from '@/router'
import dynamicRouter from '@/router/dynamic-router.js'
import { recursionRouter, nestRouter } from '@/utils/recursion-router'
const userStore = defineStore('user', {
  state: () => {
    return {
      // 动态路由
      dynamicRouter: null,
      // 菜单栏只加载了layout中的路由
      menuList: [],
      // 面包屑
      breadcrumb: [],
      // keep-alive.include
      cachedViews: [],
      // 初始路由
      userMsg: null
    }
  },
  actions: {
    login() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await loginReq()
          sessionStorage.setItem('token', res.data.token)
          resolve(res)
        } catch (error) {
          reject(error)
        }
      })
    },
    async logout() {
      await logoutReq()
      this.dynamicRouter = null
      sessionStorage.removeItem('token')
      window.location.href = window.location.origin
    },
    getDynamicRouter() {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await getInfo()
          let routes = recursionRouter(res.data.routers, dynamicRouter)
          const menu = []
          const breadcrumb = []
          const cached = []
          routes.forEach(e => {
            // 添加动态路由
            router.addRoute('layout', e)
            // 动态路由添加到菜单
            if (e.meta && !e.meta.notMenu) {
              if (e.path.split('/').length <= 2) {
                menu.push(e)
              } else {
                nestRouter(menu, e)
              }
            }
          })
          this.dynamicRouter = routes
          // 获取layout中非动态加载的路由
          for (let i = 0; i < router.options.routes.length; i++) {
            if (router.options.routes[i].name === 'layout') {
              menu.unshift(...router.options.routes[i].children)
              break
            }
          }
          router.getRoutes().forEach(e => {
            if (e.meta && !e.meta.notBreadcrumb) breadcrumb.push({ name: e.name, path: e.path, title: e.meta.title, affix: e.meta.affix })
            if (e.meta && e.meta.keepAlive) cached.push(e.name)
          })
          this.menuList = menu
          this.breadcrumb = breadcrumb
          this.cachedViews = cached
          // this.userMsg = res.data.user
          sessionStorage.setItem('userMsg', res.data.user)
          resolve(res)
        } catch (error) {
          reject(error)
        }
      })
    },
  }
})

export default userStore